package com.toman.ui.work.device;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.GetRequest;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Adpter.ItemTypeCheckAdapter;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceCheckRecordEntity;
import com.toman.JavaBean.DeviceEntity;
import com.toman.JavaBean.ReceiveSendworkOrderDto;
import com.toman.R;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.bean.ItemTypeBean;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.MyListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.leefeng.promptlibrary.PromptDialog;
import okhttp3.Request;
import okhttp3.Response;

public class TallyAddActivity extends ToolBarActivity implements ItemTypeCheckAdapter.ActionClickListener {
    ItemListAdapter adapter;
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    String shiftID = "", deviceID = "";
    @BindView(R.id.tv_device)
    TextView tvDevice;
    @BindView(R.id.rl_device)
    RelativeLayout rlDevice;
    @BindView(R.id.tv_shift)
    TextView tvShift;
    @BindView(R.id.rl_shift)
    RelativeLayout rlShift;
    @BindView(R.id.tv_remark_name)
    TextView tvRemarkName;
    @BindView(R.id.et_remark)
    EditText etRemark;

    @BindView(R.id.lv_result)
    MyListView lvResult;
    @BindView(R.id.ll)
    LinearLayout ll;
    List<ItemTypeBean> list1 = new ArrayList<ItemTypeBean>();
    ItemTypeCheckAdapter adapter1;
    //    是否点检项目有问题
    boolean isProblem = false;
    String problemName = "";
    @BindView(R.id.tv_dep)
    TextView tvDep;
    @BindView(R.id.rl_dep)
    RelativeLayout rlDep;
TextView tv_nodata;
    DeviceEntity deviceEntity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tally_add);
        ButterKnife.bind(this);
        initView();
        initToolBar("新增点检");
        initIntent();
    }

    private void initIntent() {

        if (getIntent().getSerializableExtra("bean")!=null) {
            deviceEntity = (DeviceEntity) getIntent().getSerializableExtra("bean");
            deviceID = deviceEntity.getId()+"";
            tvDevice.setText(deviceEntity.getDeviceName());
            departmentId=deviceEntity.getDepartmentId();
            tvDep.setText(deviceEntity.getDepartmentName());
            getDevice();
            shift();

        }
        else {
            tvDep.setText(departmentName);
            shift();
            device();
        }
    }


    private void initView() {
        adapter = new ItemListAdapter(this);
        adapter1 = new ItemTypeCheckAdapter(this);
        lvResult.setAdapter(adapter1);
        adapter1.setActionClickListener(this);
        adapter1.first = true;
        adapter1.isEdit(true);

        lvResult.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                checkDialog(position);
                return false;
            }


        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }
    private void checkDialog(int position) {
        ItemTypeBean bean=adapter1.getItem(position);
        String msg="";
        if (bean.getCheckIf().equals("0")){
            msg="是否将该点检项目设为不点检";
        }
        else {
            msg="是否将该点检项目设为点检";

        }
        DialogUtils.showDialog(this, msg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (bean.getCheckIf().equals("0")){
                    bean.setCheckIf("1");
                }
                else {
                    bean.setCheckIf("0");

                }
                adapter1.refreshData(list1);
            }
        });
    }

    public void shiftDialog() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);

        builder                //对话框的标题
                .setTitle("选择班次")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”


                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();
        shift();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapter.getItem(i);
                shiftID = bean.getID();
                tvShift.setText(bean.getName());
                dialog.dismiss();
            }
        });

    }

    public void deviceDialog() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);
        tv_nodata=(TextView) textEntryView.findViewById(R.id.tv_nodata);

        builder                //对话框的标题
                .setTitle("选择设备")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”


                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();
        device();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapter.getItem(i);
                deviceID = bean.getID();
                tvDevice.setText(bean.getName());
                getDevice();
                dialog.dismiss();
            }
        });

    }

    public void shift() {


        OkHttpUtils
                .get(NewBaseUrl.shift_list_get)
                .params("companyId", (String) SPUtils.get(getApplicationContext(), "cpy_id", ""))
                .params("departmentId", departmentId)
                .params("token", token)
                .params("key", "")
                .params("limit", "100")
                .params("page", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "班次列表: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            list.clear();
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("shiftName"), jsonArray.getJSONObject(i).getString("id"));
                                String startTime = jsonArray.getJSONObject(i).getString("startTime");
                                String endTime = jsonArray.getJSONObject(i).getString("endTime");
                                String tallyStartTime = jsonArray.getJSONObject(i).getString("deviceCheckStartTime");
                                String tallyEndTime = jsonArray.getJSONObject(i).getString("deviceCheckEndTime");
if (StringUtils.isNotEmpty(tallyStartTime)){
    if (TimeUtil.compareThreeTime(tallyStartTime, tallyEndTime)) {
        tvShift.setText(bean.getName());
        shiftID = bean.getID();
        list.add(bean);
    }
}
else {
    if (TimeUtil.compareThreeTime(startTime, endTime)) {
        tvShift.setText(bean.getName());
        shiftID = bean.getID();
    }
    list.add(bean);

}


                            }
                            if (list.size() == 0) {
                                ToastUtil.makeText(getApplicationContext(), "不在点检时间内");
                            }
                            adapter.refreshData(list);

                            adapter.notifyDataSetChanged();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void device() {


        GetRequest params = OkHttpUtils
                .get(NewBaseUrl.device_list_get)
                .params("departmentId", departmentId)
                .params("token", token)
                .params("key", "")
                .params("limit", "1000").params("page", "1")
                .params("moduleName","check")
                .params("filterByOperate", "1")
                ;


              params  .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "设备列表: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        list.clear();
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("deviceName"), jsonArray.getJSONObject(i).getString("id"));
                                list.add(bean);
                            }
                            if (list.size()==1){
                                tvDevice.setText(list.get(0).getName());
                                deviceID=list.get(0).getID();
                                getDevice();
                            }
                            try {
                                if (list.size() == 0) {
                                    tv_nodata.setVisibility(View.VISIBLE);
                                }
                                else {
                                    tv_nodata.setVisibility(View.GONE);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            adapter.refreshData(list);

                            adapter.notifyDataSetChanged();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void getDevice() {
        if (StringUtils.isEmpty(deviceID)){
            ToastUtil.error(getApplicationContext(),"请先选择设备");
        }
        OkHttpUtils
                .get(NewBaseUrl.device_info_get + deviceID)
                .params("token", token)
                .params("id", deviceID)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", ": 设备类别详情" + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            list1.clear();
                            JSONObject Jpage = jsonObj.getJSONObject("device");
//                            tvDep.setText(Jpage.getString("departmentName"));
//                            departmentId=jsonObj.getString("departmentId");
                            JSONObject Jpage1 = Jpage.getJSONObject("deviceTypeEntity");

                            try {
                                JSONArray jsonArray1 = Jpage1.getJSONArray("checkItemList");

                                for (int i = 0; i < jsonArray1.size(); i++) {

                                    ItemTypeBean bean1 = new ItemTypeBean();
                                    JSONObject sa = jsonArray1.getJSONObject(i);
                                    bean1.setId(sa.getString("id"));
                                    bean1.setEditable(true);
                                    bean1.setName(sa.getString("dictValue"));
                                    bean1.setNo(sa.getString("dictLabel"));
                                    bean1.setContent1(sa.getString("field1"));
                                    bean1.setContent2(sa.getString("field2Name"));
                                    bean1.setType(sa.getString("field2"));
                                    bean1.setRemark(sa.getString("remark"));
                                    bean1.setMaxNumber(sa.getString("maxNumber"));
                                    bean1.setMinNumber(sa.getString("minNumber"));
                                    bean1.setDefaultNumber(sa.getString("defaultNumber"));
                                    bean1.setStatus(sa.getString("dataStatus"));
                                    list1.add(bean1);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (list1.size() == 0) {
                                ToastUtil.makeText(getApplicationContext(), "无点检项目，请联系管理员添加");
                            }
                            adapter1.refreshData(list1);


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void add() {
        if (tvDep.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择部门");
            return;
        }

        if (StringUtils.isEmpty(deviceID)) {
            ToastUtil.makeText(getApplicationContext(), "请选择设备");
            return;
        }

        if (StringUtils.isEmpty(shiftID)) {
            ToastUtil.makeText(getApplicationContext(), "请选择班次");
            return;
        }
        StringBuilder names = new StringBuilder();

        if (list1.size() <= 0) {
            ToastUtil.makeText(getApplicationContext(), "无点检项目，请联系管理员添加");
            return;
        }
        for (int i = 0; i < list1.size(); i++) {
            ItemTypeBean bean = list1.get(i);
            if (bean.getType().equals("2")) {
                if (null == bean.getRangeInputValue()) {
                    ToastUtil.makeText(getApplicationContext(), "点检项目不得存在空值");
                    return;
                }
            }

            if (bean.getPassIf().equals("1")) {
                if (names.length() <= 0) {
                    names.append(bean.getName());
                } else {
                    names.append("、").append(bean.getName());
                }
                isProblem = true;
            }
        }
        problemName = names.toString();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("departmentId", departmentId);
        map.put("deviceId", deviceID);
        map.put("shiftId", shiftID);
        map.put("remark", etRemark.getText().toString());
        map.put("checkResults", list1);

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.devicecheckrecord_save)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "班次: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            if (isProblem) {
                                problemDialog();
                            } else {

                                ToastUtil.success(getApplicationContext(), jsonObj.getString("msg"));

                                finish();
                            }

                        } else {
                            ToastUtil.error(getApplicationContext(),jsonObj.getString("msg"));
                        }

                    }
                });
    }

    @OnClick({R.id.tv_device, R.id.tv_shift,R.id.tv_dep})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_device:
                deviceDialog();
                break;
            case R.id.tv_shift:
                shiftDialog();
                break;
            case R.id.tv_dep:
                DialogUtils.showDialog(this, NetworkEnum.DEP, mCompanyId, new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        departmentId=bean1.getID();
                        tvDep.setText(bean1.getName());
                        list1.clear();
                        adapter1.refreshData(list1);
                        tvDevice.setText(null);
                        deviceID=null;
                        shiftID=null;
                        tvShift.setText(null);
                        dialog.dismiss();
                    }
                });
                break;
        }
    }

    public void problemDialog() {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("有点检项目不通过，是否跳转生成报修单")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Bundle bundle = new Bundle();
                        bundle.putString("problemName", problemName);
                        bundle.putString("status", "1");
                        bundle.putString("deviceId", deviceID);
                        bundle.putString("deviceName", tvDevice.getText().toString());
                        bundle.putString("id", getIntent().getStringExtra("id"));

                        bundle.putString("deviceName", tvDevice.getText().toString());
                        ToastUtil.makeText(getApplicationContext(), "点检成功，跳转至报修单页面");
                        IntentUtils.startActivity(TallyAddActivity.this, DeviceRepairAddActivity.class, bundle);

                        finish();

                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ToastUtil.makeText(getApplicationContext(), "点检成功，未生成报修单");

                        finish();
                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    @Override
    public void onDetailClick(ItemTypeBean bean) {
        message(1, bean);
    }

    @Override
    public void onCheckClick(ItemTypeBean bean) {

    }

    public void message(int type, ItemTypeBean bean) {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        View v = factory.inflate(R.layout.dialog_item_type, null);

        TextView content1 = (TextView) v.findViewById(R.id.tv_content1);
        TextView content2 = (TextView) v.findViewById(R.id.tv_content2);
        TextView content3 = (TextView) v.findViewById(R.id.tv_content3);
        TextView content4 = (TextView) v.findViewById(R.id.tv_content4);
        TextView content5 = (TextView) v.findViewById(R.id.tv_content5);
        TextView content6 = (TextView) v.findViewById(R.id.tv_content6);
        TextView tv_max = (TextView) v.findViewById(R.id.tv_max);
        TextView tv_min = (TextView) v.findViewById(R.id.tv_min);
        TextView tv_default = (TextView) v.findViewById(R.id.tv_default);
        RelativeLayout rl3 = (RelativeLayout) v.findViewById(R.id.rl3);
        RelativeLayout rl4 = (RelativeLayout) v.findViewById(R.id.rl4);
        RelativeLayout rl_max = (RelativeLayout) v.findViewById(R.id.rl_max);
        RelativeLayout rl_min = (RelativeLayout) v.findViewById(R.id.rl_min);
        RelativeLayout rl_default = (RelativeLayout) v.findViewById(R.id.rl_default);
        content1.setText(bean.getNo());
        content2.setText(bean.getName());

        content5.setText(bean.getRemark());
        content6.setText(bean.getStatus());
        if (type == 1) {
            content3.setText(bean.getContent1());
            content4.setText(bean.getContent2());
        } else {
            rl3.setVisibility(View.GONE);
            rl4.setVisibility(View.GONE);

        }
        if (bean.getType().equals("2")) {
            rl_max.setVisibility(View.VISIBLE);
            rl_min.setVisibility(View.VISIBLE);
            rl_default.setVisibility(View.VISIBLE);
            tv_max.setText(bean.getMaxNumber());
            tv_min.setText(bean.getMinNumber());
            tv_default.setText(bean.getDefaultNumber());
        }

        builder                //对话框的标题
                .setTitle(bean.getName())
                //设定显示的View
                .setView(v)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {


                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();

    }
}
